import { useState, useEffect, useContext, useRef, useCallback } from 'react';
import { cn } from '@/lib/utils';
import { useTheme } from '@/hooks/useTheme';
import { toast } from 'sonner';
import { AuthContext } from '@/App';
import api, { ApiResponse } from '@/services/api';
import { MilkdownPreview } from '@/components/MilkdownPreview';
import { motion, AnimatePresence } from 'framer-motion';
import { emojiCategories } from '@/lib/emoji-data';
import { generateTable } from '@/lib/editor-utils';
import { DocumentData } from '@/lib/types';
import { createPatch } from "diff";
import sha256 from "js-sha256";
import { addVersion } from "@/services/api";

interface EditorModalProps {
  isOpen: boolean;
  onClose: () => void;
  onBeforeClose?: () => Promise<void>;
  docId: string;
  onSaveSuccess: () => void;
}

export default function EditorModal({ isOpen, onClose, onBeforeClose, docId, onSaveSuccess }: EditorModalProps) {
  const { theme, toggleTheme, isDark } = useTheme();
  const { isAuthenticated } = useContext(AuthContext) as any;
  
  const [content, setContent] = useState('');
  const [title, setTitle] = useState('');
  const [teamId, setTeamId] = useState('');
  const [projectId, setProjectId] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [wordCount, setWordCount] = useState(0);
  const [charCount, setCharCount] = useState(0);
  const [isEditMode, setIsEditMode] = useState(false);
  const [showTableModal, setShowTableModal] = useState(false);
  const [showCodeBlockModal, setShowCodeBlockModal] = useState(false);
  const [isEditingTitle, setIsEditingTitle] = useState(false);
  const [autoSaveTimer, setAutoSaveTimer] = useState<number | null>(null);
  const [lastSavedContent, setLastSavedContent] = useState('');
  const [lastSavedTitle, setLastSavedTitle] = useState('');
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [selectedLanguage, setSelectedLanguage] = useState('json');
  const [codeBlockContent, setCodeBlockContent] = useState('');
  const [tableConfig, setTableConfig] = useState({
    rows: 3,
    cols: 3,
    alignment: 'center'
  });
  const [clearedContent, setClearedContent] = useState<string>('');
  const [canUndoClear, setCanUndoClear] = useState(false);
  const [showEmojiModal, setShowEmojiModal] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState(0);
  const [originalContent, setOriginalContent] = useState('');
  const [originalTitle, setOriginalTitle] = useState('');
  const [showTemplateModal, setShowTemplateModal] = useState(false);
  const [templates, setTemplates] = useState<any[]>([]);
  const [selectedTemplateType, setSelectedTemplateType] = useState<'SELF' | 'SYS'>('SELF');
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);
  const [showSaveTemplateModal, setShowSaveTemplateModal] = useState(false);
  const [templateTitle, setTemplateTitle] = useState('');

  const editorRef = useRef<HTMLDivElement>(null);
  const previewRef = useRef<HTMLDivElement>(null);
  const [isScrolling, setIsScrolling] = useState(false);

  // 使用 useRef 来存储最新的 content 值，避免闭包问题
  const contentRef = useRef(content);
  const titleRef = useRef(title);

  // 同步 ref 和 state
  useEffect(() => {
    contentRef.current = content;
  }, [content]);

  useEffect(() => {
    titleRef.current = title;
  }, [title]);

  // 同步滚动功能
  const handleEditorScroll = (e: React.UIEvent<HTMLTextAreaElement>) => {
    if (isScrolling || isEditMode) return;
    
    setIsScrolling(true);
    const textarea = e.target as HTMLTextAreaElement;
    const scrollTop = textarea.scrollTop;
    const scrollHeight = textarea.scrollHeight;
    const clientHeight = textarea.clientHeight;
    
    const scrollRatio = scrollTop / (scrollHeight - clientHeight);
    
    if (previewRef.current) {
      const previewScrollContainer = previewRef.current.querySelector('.overflow-y-auto') as HTMLElement;
      if (previewScrollContainer) {
        const previewScrollHeight = previewScrollContainer.scrollHeight;
        const previewClientHeight = previewScrollContainer.clientHeight;
        const targetScrollTop = scrollRatio * (previewScrollHeight - previewClientHeight);
        previewScrollContainer.scrollTop = targetScrollTop;
      }
    }
    
    setTimeout(() => setIsScrolling(false), 50);
  };

  // 计算字数统计
  useEffect(() => {
    const words = content.trim() ? content.trim().split(/\s+/).length : 0;
    const chars = content.length;
    setWordCount(words);
    setCharCount(chars);
  }, [content]);

  // 加载文档数据
  useEffect(() => {
    if (isOpen && docId) {
      loadDocumentData();
    }
  }, [isOpen, docId]);

  const loadDocumentData = async () => {
    try {
      setIsLoading(true);
      
      const res: ApiResponse = await api({
        url: '/doc/getDocByDocId',
        method: 'post',
        data: { docId }
      });

      if (res && res.success && res.data) {
        const docData = res.data;
        setContent(docData.docContent || '');
        setTitle(docData.docTitle || '');
        setTeamId(docData.teamId || '');
        setProjectId(docData.projectId || '');
        setLastSavedContent(docData.docContent || '');
        setLastSavedTitle(docData.docTitle || '');
        setOriginalContent(docData.docContent || '');
        setOriginalTitle(docData.docTitle || '');
      } else {
        throw new Error(res?.message || '获取文档信息失败');
      }
    } catch (error: any) {
      console.error('加载文档数据失败:', error);
      toast.error(error.message || '加载文档数据失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 保存文档 - 使用 useCallback 确保获取最新状态
  const handleSave = useCallback(async () => {
    if (!docId) {
      toast.error('文档ID不存在');
      return;
    }

    try {
      setIsSaving(true);
      // 使用 ref 中的最新值，确保获取到当前编辑的内容
      const currentContent = contentRef.current;
      const currentTitle = titleRef.current;
      
      console.log('EditorModal 保存文档:', {
        docId,
        docTitle: currentTitle,
        docContent: currentContent,
        contentLength: currentContent.length
      });

      const res: ApiResponse = await api({
        url: '/doc/editDoc',
        method: 'post',
        data: {
          docId: docId,
          docTitle: currentTitle,
          docContent: currentContent,
          docIcon: 'fa-solid fa-file-lines'
        },
        timeout: 10000
      });

      if (res && res.success) {
        toast.success('文档已保存', {
          style: {
            color: '#10b981'
          }
        });
        setLastSavedContent(currentContent);
        setLastSavedTitle(currentTitle);
        onSaveSuccess();
      } else {
        throw new Error(res?.message || '保存失败');
      }
    } catch (error: any) {
      console.error('保存文档失败:', error);
      toast.error(error.message || '保存文档失败');
    } finally {
      setIsSaving(false);
    }
  }, [docId, onSaveSuccess]);

  // 自动保存函数 - 使用 useCallback
  const handleAutoSave = useCallback(async () => {
    const currentContent = contentRef.current;
    const currentTitle = titleRef.current;
    
    if (currentContent.trim() !== '' || currentTitle.trim() !== '') {
      await handleSave();
    }
  }, [handleSave]);

  // 设置自动保存定时器
  const setupAutoSaveTimer = useCallback(() => {
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer);
    }
    
    const timer = window.setTimeout(() => {
      handleAutoSave();
      setAutoSaveTimer(null);
    }, 5000);
    
    setAutoSaveTimer(timer);
  }, [autoSaveTimer, handleAutoSave]);

  // 处理内容变化
  const handleContentChange = useCallback((newContent: string) => {
    setContent(newContent);
    // 如果用户开始编辑新内容，重置撤回状态
    if (canUndoClear && newContent !== clearedContent) {
      setCanUndoClear(false);
      setClearedContent('');
    }
    setupAutoSaveTimer();
  }, [canUndoClear, clearedContent, setupAutoSaveTimer]);

  // 处理工具栏工具的内容变化（不触发自动保存）
  const handleToolbarContentChange = useCallback((newContent: string) => {
    setContent(newContent);
    // 如果用户开始编辑新内容，重置撤回状态
    if (canUndoClear && newContent !== clearedContent) {
      setCanUndoClear(false);
      setClearedContent('');
    }
    // 不调用 setupAutoSaveTimer()，避免工具栏操作触发自动保存
  }, [canUndoClear, clearedContent]);

  // 处理点击编辑区外部
  const handleClickOutside = useCallback(() => {
    const currentContent = contentRef.current;
    const currentTitle = titleRef.current;
    
    if (currentContent.trim() !== '' || currentTitle.trim() !== '') {
      handleAutoSave();
    }
  }, [handleAutoSave]);

  // 切换全屏模式
  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  // 插入多语言代码块
  const insertCodeBlock = () => {
    const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const selectedText = content.substring(start, end);
      
      // 如果有选中的文本，使用选中的文本作为代码内容
      if (selectedText) {
        setCodeBlockContent(selectedText);
      } else {
        setCodeBlockContent('');
      }
      
      setShowCodeBlockModal(true);
    }
  };

  // 确认插入代码块
  const confirmCodeBlock = () => {
    const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
    if (textarea) {
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const currentContent = contentRef.current;
      const selectedText = currentContent.substring(start, end);
      
      const codeBlock = `\n\`\`\`${selectedLanguage}\n${codeBlockContent}\n\`\`\`\n`;
      const newText = currentContent.substring(0, start) + codeBlock + currentContent.substring(end);
      handleToolbarContentChange(newText);
      
      // 设置光标位置到代码块后面
      setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(start + codeBlock.length, start + codeBlock.length);
      }, 0);
    }
    
    setShowCodeBlockModal(false);
    setCodeBlockContent('');
    setSelectedLanguage('json');
  };

  // 插入表格
  const insertTable = () => {
    const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
    if (textarea) {
      const start = textarea.selectionStart;
      const currentContent = contentRef.current;
      const table = generateTable(tableConfig.rows, tableConfig.cols, tableConfig.alignment);
      const newText = currentContent.substring(0, start) + '\n' + table + '\n' + currentContent.substring(start);
      handleToolbarContentChange(newText);
      
      setTimeout(() => {
        textarea.focus();
        const newPosition = start + table.length + 2;
        textarea.setSelectionRange(newPosition, newPosition);
      }, 0);
    }
    setShowTableModal(false);
  };

  // 快捷键支持
  useEffect(() => {
    if (!isOpen) return;
    
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        handleSave();
      } else if (e.key === 'Escape') {
        e.preventDefault();
        if (isFullscreen) {
          setIsFullscreen(false);
        } else {
          onClose();
        }
      }
    };
    
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, isFullscreen]);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer);
      }
    };
  }, [autoSaveTimer]);

  // 获取内容 diff
  const getDiffContent = (oldContent: string, newContent: string) => {
    const diff = createPatch('doc', oldContent, newContent);
    return diff;
  };

  // 获取内容 hash
  const getContentHash = (content: string) => {
    return sha256.sha256(content);
  };

  // 关闭弹框
  const handleBeforeClose = async () => {
    const oldContent = originalContent;
    const currentContent = contentRef.current;
    const currentTitle = titleRef.current;
    
    console.log('[EditorModal] handleBeforeClose called', { 
      docId, 
      oldContent, 
      currentContent, 
      currentTitle,
      contentLength: currentContent.length 
    });
    
    if (
      docId &&
      (currentContent !== oldContent) &&
      (currentContent.trim() !== '' || currentTitle.trim() !== '')
    ) {
      console.log('[EditorModal] 内容有变化，准备保存和保存版本');
      await handleSave();
      console.log('[EditorModal] 保存文档完成，准备调用 addVersion', {
        docId,
        docContent: currentContent,
        diffContent: getDiffContent(oldContent, currentContent),
        isCurrent: true,
        contentHash: getContentHash(currentContent)
      });
      await addVersion({
        docId,
        docContent: currentContent,
        diffContent: getDiffContent(oldContent, currentContent),
        isCurrent: true,
        contentHash: getContentHash(currentContent)
      });
      console.log('[EditorModal] addVersion 调用完成');
      onSaveSuccess();
    } else if (currentContent.trim() !== '' || currentTitle.trim() !== '') {
      console.log('[EditorModal] 内容无变化，仅保存');
      await handleSave();
      onSaveSuccess();
    } else {
      console.log('[EditorModal] 内容和标题均为空，不保存');
    }
  };

  // 加载模板列表
  const loadTemplates = async (type: 'SELF' | 'SYS') => {
    console.log('loadTemplates被调用，type:', type, 'teamId:', teamId, 'projectId:', projectId);
    try {
      setIsLoadingTemplates(true);
      const res = await api({
        url: '/doc/tmp/listTmp',
        method: 'post',
        data: {
          teamId: teamId,
          projectId: projectId,
          type
        }
      });
      const realRes = res.data ? res.data : res;
      console.log('模板接口最终数据 realRes:', realRes);
      if (Array.isArray(realRes)) {
        setTemplates(realRes);
        console.log('setTemplates:', realRes);
      } else if (realRes && realRes.success) {
        setTemplates(realRes.data || []);
        console.log('setTemplates:', realRes.data);
      } else {
        throw new Error(realRes?.message || '获取模板列表失败');
      }
    } catch (error: any) {
      toast.error(error.message || '获取模板列表失败');
    } finally {
      setIsLoadingTemplates(false);
    }
  };

  // 应用模板
  const handleApplyTemplate = (template: any) => {
    setContent(template.tmpContent || '');
    setShowTemplateModal(false);
    toast.success('模板应用成功');
  };

  // 保存为模板
  const handleSaveAsTemplate = async () => {
    if (!templateTitle.trim()) {
      toast.error('请输入模板标题');
      return;
    }
    if (!teamId || !projectId) {
      toast.error('缺少团队ID或项目ID');
      return;
    }
    try {
      const res = await api({
        url: '/doc/tmp/addTmp',
        method: 'post',
        data: {
          tmpTitle: templateTitle.trim(),
          tmpContent: content,
          teamId,
          projectId,
          type: 'SELF'
        }
      });
      if (res && res.data && res.data.success) {
        toast.success('模板保存成功');
        setShowSaveTemplateModal(false);
        setTemplateTitle('');
        // 重新加载模板列表
        loadTemplates(selectedTemplateType);
      } else {
        throw new Error(res?.data?.message || '保存模板失败');
      }
    } catch (error: any) {
      toast.error(error.message || '保存模板失败');
    }
  };

  if (isLoading) {
    return (
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center"
          >
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className="flex flex-col items-center space-y-4 p-8 rounded-2xl bg-white dark:bg-gray-800"
            >
              <div className="w-16 h-16 rounded-full flex items-center justify-center pulse-glow bg-blue-600/20">
                <i className="fa-solid fa-spinner fa-spin text-2xl text-blue-400"></i>
              </div>
              <span className="text-lg font-medium">加载文档中...</span>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    );
  }

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className={cn(
            "fixed inset-0 z-50 flex items-center justify-center",
            isFullscreen 
              ? "bg-gray-900 dark:bg-black" 
              : "bg-black/50 backdrop-blur-sm p-4"
          )}
        >
          <motion.div
            initial={{ scale: 0.9, opacity: 0, y: 20 }}
            animate={{ scale: 1, opacity: 1, y: 0 }}
            exit={{ scale: 0.9, opacity: 0, y: 20 }}
            className={cn(
              "flex flex-col rounded-2xl shadow-2xl overflow-hidden",
              isFullscreen 
                ? "w-full h-full rounded-none" 
                : "w-full max-w-[95vw] h-[95vh]",
              isDark ? "bg-gray-900 border border-gray-700" : "bg-white border border-gray-200"
            )}
          >
            {/* 顶部导航栏 */}
            <motion.header 
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              className={cn(
                "flex-shrink-0 py-0.5 px-1 border-b backdrop-blur-xl bg-opacity-95 shadow-lg",
                isDark ? "bg-gray-800/95 border-gray-700" : "bg-white/95 border-gray-200"
              )}
            >
              <div className="container mx-auto flex justify-between items-center">
                <div className="flex items-center space-x-6">
                  {!isFullscreen && (
                  <motion.button 
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={async () => { if (typeof onBeforeClose === 'function') { await onBeforeClose(); } else { await handleBeforeClose(); } onClose(); }}
                    className={cn(
                      "px-4 py-2 rounded-lg font-medium flex items-center transition-all duration-200",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-200 hover:text-white" 
                        : "bg-gray-100 hover:bg-gray-200 text-gray-700 hover:text-gray-900"
                    )}
                  >
                    <i className="fa-solid fa-times mr-2"></i>
                    关闭
                  </motion.button>
                  )}
                  <div className="flex flex-col">
                    {isEditingTitle ? (
                      <div className="flex items-center space-x-2">
                        <input
                          type="text"
                          value={title}
                          onChange={(e) => {
                            setTitle(e.target.value);
                            setupAutoSaveTimer();
                          }}
                          onBlur={() => {
                            setIsEditingTitle(false);
                            handleClickOutside();
                          }}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                              setIsEditingTitle(false);
                              handleClickOutside();
                            } else if (e.key === 'Escape') {
                              setIsEditingTitle(false);
                            }
                          }}
                          className={cn(
                            "font-bold text-2xl bg-transparent border-b-2 border-blue-500 outline-none px-1",
                            isDark ? "text-white" : "text-gray-900"
                          )}
                          autoFocus
                        />
                        <button
                          onClick={() => setIsEditingTitle(false)}
                          className={cn(
                            "w-6 h-6 rounded-full flex items-center justify-center transition-colors",
                            isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                          )}
                        >
                          <i className="fa-solid fa-check text-sm"></i>
                        </button>
                      </div>
                    ) : (
                      <div className="flex items-center space-x-2 group">
                        <h1 
                          className="font-bold text-2xl bg-gradient-to-r from-blue-600 to-orange-500 bg-clip-text text-transparent cursor-pointer hover:opacity-80 transition-opacity"
                          onClick={() => setIsEditingTitle(true)}
                        >
                          {title}
                        </h1>
                        <button
                          onClick={() => setIsEditingTitle(true)}
                          className={cn(
                            "w-6 h-6 rounded-full flex items-center justify-center transition-colors opacity-0 group-hover:opacity-100",
                            isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                          )}
                        >
                          <i className="fa-solid fa-edit text-sm"></i>
                        </button>
                      </div>
                    )}
                  </div>
                </div>
                
                <div className="flex items-center space-x-4">
                  <motion.button
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={handleSave}
                    disabled={isSaving}
                    className={cn(
                      "px-4 py-2 rounded-lg font-medium transition-all duration-200 shadow-lg ripple-button",
                      isSaving
                        ? "opacity-50 cursor-not-allowed"
                        : "hover:shadow-xl",
                      isDark 
                        ? "bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white" 
                        : "bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white"
                    )}
                  >
                    {isSaving ? (
                      <>
                        <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                        保存中...
                      </>
                    ) : (
                      <>
                        <i className="fa-solid fa-save mr-2"></i>
                        保存文档
                      </>
                    )}
                  </motion.button>
                  <motion.button 
                    whileHover={{ scale: 1.1, rotate: 180 }}
                    whileTap={{ scale: 0.9 }}
                    onClick={toggleTheme}
                    className={cn(
                      "w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300 shadow-lg",
                      isDark 
                        ? "bg-gradient-to-r from-gray-700 to-gray-600 hover:from-gray-600 hover:to-gray-500 text-yellow-400" 
                        : "bg-gradient-to-r from-gray-200 to-gray-300 hover:from-gray-300 hover:to-gray-400 text-gray-700"
                    )}
                  >
                    <i className={isDark ? "fa-solid fa-sun" : "fa-solid fa-moon"}></i>
                  </motion.button>
                </div>
              </div>
            </motion.header>

            {/* Markdown工具栏 */}
            <div className={cn(
              "flex-shrink-0 p-3 border-b",
              isDark ? "bg-gray-800/60 border-gray-700" : "bg-gray-50/60 border-gray-200"
            )}>
              <div className="container mx-auto flex items-center justify-center space-x-2 flex-wrap gap-2">
                {/* 文本格式工具 */}
                {[
                  { icon: 'fa-solid fa-bold', syntax: '**', tooltip: '粗体文本' },
                  { icon: 'fa-solid fa-italic', syntax: '*', tooltip: '斜体文本' },
                  { icon: 'fa-solid fa-strikethrough', syntax: '~~', tooltip: '删除线文本' }
                ].map((item, index) => (
                  <motion.button
                    key={`format-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const selectedText = content.substring(start, end);
                        const newText = content.substring(0, start) + item.syntax + (selectedText || '文本') + item.syntax + content.substring(end);
                        handleToolbarContentChange(newText);
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          if (selectedText) {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                          } else {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + 2);
                          }
                        }, 0);
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <i className={item.icon}></i>
                  </motion.button>
                ))}

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 列表工具 */}
                {[
                  { icon: 'fa-solid fa-list-ul', syntax: '- ', tooltip: '无序列表' },
                  { icon: 'fa-solid fa-list-ol', syntax: '1. ', tooltip: '有序列表' }
                ].map((item, index) => (
                  <motion.button
                    key={`list-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const selectedText = content.substring(start, end);
                        const newText = content.substring(0, start) + item.syntax + (selectedText || '列表项目') + content.substring(end);
                        handleToolbarContentChange(newText);
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          if (selectedText) {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                          } else {
                            textarea.setSelectionRange(start + item.syntax.length + 5, start + item.syntax.length + 5);
                          }
                        }, 0);
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <i className={item.icon}></i>
                  </motion.button>
                ))}

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 引用和分界线 */}
                {[
                  { icon: 'fa-solid fa-quote-left', syntax: '> ', tooltip: '引用块' },
                  { icon: 'fa-solid fa-minus', syntax: '\n---\n', tooltip: '水平分界线' }
                ].map((item, index) => (
                  <motion.button
                    key={`block-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const selectedText = content.substring(start, end);
                        const newText = content.substring(0, start) + item.syntax + (selectedText || '引用内容') + content.substring(end);
                        handleToolbarContentChange(newText);
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          if (selectedText) {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                          } else {
                            textarea.setSelectionRange(start + item.syntax.length + 4, start + item.syntax.length + 4);
                          }
                        }, 0);
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <i className={item.icon}></i>
                  </motion.button>
                ))}

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 标题工具 */}
                {[
                  { icon: 'H1', syntax: '# ', tooltip: '一级标题 (H1)' },
                  { icon: 'H2', syntax: '## ', tooltip: '二级标题 (H2)' },
                  { icon: 'H3', syntax: '### ', tooltip: '三级标题 (H3)' },
                  { icon: 'H4', syntax: '#### ', tooltip: '四级标题 (H4)' },
                  { icon: 'H5', syntax: '##### ', tooltip: '五级标题 (H5)' },
                  { icon: 'H6', syntax: '###### ', tooltip: '六级标题 (H6)' }
                ].map((item, index) => (
                  <motion.button
                    key={`heading-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const selectedText = content.substring(start, end);
                        const newText = content.substring(0, start) + item.syntax + (selectedText || '标题') + content.substring(end);
                        handleToolbarContentChange(newText);
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          if (selectedText) {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                          } else {
                            textarea.setSelectionRange(start + item.syntax.length + 2, start + item.syntax.length + 2);
                          }
                        }, 0);
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <span className="text-xs font-bold">{item.icon}</span>
                  </motion.button>
                ))}

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 代码块工具 */}
                {[
                  { icon: 'fa-solid fa-code', syntax: '`', tooltip: '行内代码' }
                ].map((item, index) => (
                  <motion.button
                    key={`inline-code-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const selectedText = content.substring(start, end);
                        const newText = content.substring(0, start) + item.syntax + (selectedText || '代码') + item.syntax + content.substring(end);
                        handleToolbarContentChange(newText);
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          if (selectedText) {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + selectedText.length);
                          } else {
                            textarea.setSelectionRange(start + item.syntax.length, start + item.syntax.length + 2);
                          }
                        }, 0);
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <i className={item.icon}></i>
                  </motion.button>
                ))}

                {/* 多语言代码块工具 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={insertCodeBlock}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                      : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                  )}
                  title="插入多语言代码块"
                >
                  <i className="fa-solid fa-file-code"></i>
                </motion.button>

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>
                
                {/* 表格按钮 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setShowTableModal(true)}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                      : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                  )}
                  title="插入表格"
                >
                  <i className="fa-solid fa-table"></i>
                </motion.button>

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 链接工具 */}
                {[
                  { icon: 'fa-solid fa-link', syntax: '[链接文本](URL)', tooltip: '插入链接' },
                  { icon: 'fa-solid fa-image', syntax: '![alt文本](图片URL)', tooltip: '插入图片' },
                  { icon: 'fa-solid fa-video', syntax: '![视频](视频URL)', tooltip: '插入视频链接' }
                ].map((item, index) => (
                  <motion.button
                    key={`link-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        const selectedText = content.substring(start, end);
                        const newText = content.substring(0, start) + item.syntax + content.substring(end);
                        handleToolbarContentChange(newText);
                        // 设置光标位置
                        setTimeout(() => {
                          textarea.focus();
                          if (item.syntax.includes('链接文本')) {
                            textarea.setSelectionRange(start + 1, start + 5);
                          } else if (item.syntax.includes('alt文本')) {
                            textarea.setSelectionRange(start + 2, start + 8);
                          } else {
                            textarea.setSelectionRange(start + 2, start + 4);
                          }
                        }, 0);
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <i className={item.icon}></i>
                  </motion.button>
                ))}

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 表情包按钮 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setShowEmojiModal(true)}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                      : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                  )}
                  title="插入表情包"
                >
                  <span className="text-lg">😊</span>
                </motion.button>

                {/* 分隔线 */}
                <div className={cn(
                  "w-px h-6",
                  isDark ? "bg-gray-600" : "bg-gray-300"
                )}></div>

                {/* 实用工具 */}
                {[
                  { icon: 'fa-solid fa-calendar', syntax: '', tooltip: '插入当前日期时间' },
                  { icon: 'fa-solid fa-file-lines', syntax: '\n<div style="page-break-after: always;"></div>\n', tooltip: '插入分页符' }
                ].map((item, index) => (
                  <motion.button
                    key={`util-${index}`}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        const start = textarea.selectionStart;
                        const end = textarea.selectionEnd;
                        let newText;
                        let insertedLength = 0;
                        
                        if (item.syntax === '') {
                          const now = new Date();
                          const year = now.getFullYear();
                          const month = String(now.getMonth() + 1).padStart(2, '0');
                          const day = String(now.getDate()).padStart(2, '0');
                          const hours = String(now.getHours()).padStart(2, '0');
                          const minutes = String(now.getMinutes()).padStart(2, '0');
                          const seconds = String(now.getSeconds()).padStart(2, '0');
                          const dateStr = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                          newText = content.substring(0, start) + dateStr + content.substring(end);
                          insertedLength = dateStr.length;
                        } else {
                          newText = content.substring(0, start) + item.syntax + content.substring(end);
                          insertedLength = item.syntax.length;
                        }
                        
                        handleToolbarContentChange(newText);
                        
                        // 立即设置光标位置并聚焦
                        textarea.focus();
                        textarea.setSelectionRange(start + insertedLength, start + insertedLength);
                        
                        // 确保编辑区可见
                        textarea.scrollIntoView({ behavior: 'smooth', block: 'center' });
                      }
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                    )}
                    title={item.tooltip}
                  >
                    <i className={item.icon}></i>
                  </motion.button>
                ))}

                {/* 清空内容按钮 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => {
                    if (content.trim()) {
                      if (confirm('确定要清空所有内容吗？您可以点击撤回按钮恢复内容。')) {
                        setClearedContent(content);
                        setCanUndoClear(true);
                        setContent('');
                        const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                        if (textarea) {
                          textarea.focus();
                        }
                        toast.success('内容已清空，可以点击撤回按钮恢复');
                      }
                    } else {
                      toast.info('编辑器已经是空的');
                    }
                  }}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isDark 
                      ? "bg-red-700 hover:bg-red-600 text-red-300 hover:text-white" 
                      : "bg-red-200 hover:bg-red-300 text-red-700 hover:text-red-900"
                  )}
                  title="清空所有内容"
                >
                  <i className="fa-solid fa-trash"></i>
                </motion.button>

                {/* 撤回清空按钮 */}
                {canUndoClear && (
                  <motion.button
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => {
                      setContent(clearedContent);
                      setCanUndoClear(false);
                      setClearedContent('');
                      const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                      if (textarea) {
                        textarea.focus();
                      }
                      toast.success('内容已恢复');
                    }}
                    className={cn(
                      "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                      isDark 
                        ? "bg-green-700 hover:bg-green-600 text-green-300 hover:text-white" 
                        : "bg-green-200 hover:bg-green-300 text-green-700 hover:text-green-900"
                    )}
                    title="撤回清空操作"
                  >
                    <i className="fa-solid fa-undo"></i>
                  </motion.button>
                )}

                {/* 全屏按钮 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={toggleFullscreen}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isFullscreen
                      ? "bg-blue-600 hover:bg-blue-700 text-white"
                      : isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                  )}
                  title={isFullscreen ? "退出全屏 (按ESC退出)" : "全屏 (按ESC退出)"}
                >
                  <i className={isFullscreen ? "fa-solid fa-compress" : "fa-solid fa-expand"}></i>
                </motion.button>

                {/* 模板按钮 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => {
                    console.log('模板按钮被点击');
                    setShowTemplateModal(true);
                    loadTemplates(selectedTemplateType);
                  }}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isDark 
                      ? "bg-gray-700 hover:bg-gray-600 text-gray-300 hover:text-white" 
                      : "bg-gray-200 hover:bg-gray-300 text-gray-700 hover:text-gray-900"
                  )}
                  title="模板"
                >
                  <i className="fa-solid fa-layer-group"></i>
                </motion.button>

                {/* 保存为模板按钮 */}
                <motion.button
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                  onClick={() => setShowSaveTemplateModal(true)}
                  className={cn(
                    "w-8 h-8 rounded flex items-center justify-center transition-all duration-200 toolbar-button ripple-button",
                    isDark 
                      ? "bg-purple-700 hover:bg-purple-800 text-white" 
                      : "bg-purple-500 hover:bg-purple-600 text-white"
                  )}
                  title="保存为模板"
                >
                  <i className="fa-solid fa-bookmark"></i>
                </motion.button>
              </div>
            </div>

            {/* 主内容区域 */}
            <main className="flex-1 flex min-h-0 overflow-hidden">
              <div className={cn(
                "w-full h-full",
                isFullscreen 
                  ? "flex gap-6" 
                  : isEditMode 
                    ? "flex justify-center" 
                    : "max-w-7xl mx-auto flex gap-6"
              )}>
                {/* 左侧编辑器 */}
                <motion.div 
                  initial={{ opacity: 0, x: -50 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="flex flex-col relative h-full"
                  style={{ 
                    width: isFullscreen 
                      ? (isEditMode ? '100%' : '50%')
                      : isEditMode 
                        ? '800px' 
                        : '50%', 
                    minWidth: isFullscreen 
                      ? (isEditMode ? '100%' : '400px')
                      : isEditMode 
                        ? '600px' 
                        : '300px',
                    maxWidth: isFullscreen 
                      ? 'none'
                      : isEditMode 
                        ? '800px' 
                        : 'none'
                  }}
                  ref={editorRef}
                >
                  <div className={cn(
                    "flex-shrink-0 p-2 border-b rounded-t-xl",
                    isDark ? "bg-gray-800/80 border-gray-700" : "bg-white/80 border-gray-200"
                  )}>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4 text-xs text-gray-500">
                        <span>字数: {wordCount}</span>
                        <span>字符: {charCount}</span>
                      </div>
                      {isEditMode && (
                        <motion.button
                          whileHover={{ scale: 1.05 }}
                          whileTap={{ scale: 0.95 }}
                          onClick={() => setIsEditMode(false)}
                          className="text-sm font-medium text-gray-600 dark:text-gray-400 flex items-center hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                          title="切换回预览模式"
                        >
                          <i className="fa-solid fa-eye mr-2"></i>
                          预览
                        </motion.button>
                      )}
                    </div>
                  </div>
                  
                  <div className={cn(
                    "flex-1 overflow-hidden rounded-b-xl shadow-xl",
                    isDark ? "bg-gray-900/80" : "bg-white/80"
                  )}>
                    <textarea
                      value={content}
                      onChange={(e) => handleContentChange(e.target.value)}
                      onBlur={handleClickOutside}
                      onScroll={handleEditorScroll}
                      className={cn(
                        "w-full h-full p-6 resize-none border-0 outline-none font-mono text-sm leading-relaxed editor-textarea custom-scrollbar",
                        isDark 
                          ? "bg-gray-900/80 text-gray-100 placeholder-gray-500" 
                          : "bg-white/80 text-gray-900 placeholder-gray-400"
                      )}
                      placeholder="请输入Markdown内容..."
                    />
                  </div>
                </motion.div>

                {/* 可拖动的分界线 */}
                {!isEditMode && (
                  <div 
                    className={cn(
                      "w-1 cursor-col-resize flex-shrink-0 rounded bg-gray-300 dark:bg-gray-700 transition-colors duration-200",
                      "hover:bg-blue-400 dark:hover:bg-blue-500"
                    )}
                    style={{ minHeight: '480px', margin: '0 0' }}
                    onMouseDown={(e) => {
                      e.preventDefault();
                      const startX = e.clientX;
                      const startEditorWidth = editorRef.current?.clientWidth || 400;
                      const startPreviewWidth = previewRef.current?.clientWidth || 400;
                      
                      const handleMouseMove = (moveEvent: MouseEvent) => {
                        const dx = moveEvent.clientX - startX;
                        const newEditorWidth = Math.max(300, Math.min(800, startEditorWidth + dx));
                        const newPreviewWidth = Math.max(300, startPreviewWidth - dx);
                        
                        if (editorRef.current) {
                          editorRef.current.style.width = `${newEditorWidth}px`;
                        }
                        if (previewRef.current) {
                          previewRef.current.style.width = `${newPreviewWidth}px`;
                        }
                      };

                      const handleMouseUp = () => {
                        document.removeEventListener('mousemove', handleMouseMove);
                        document.removeEventListener('mouseup', handleMouseUp);
                      };

                      document.addEventListener('mousemove', handleMouseMove);
                      document.addEventListener('mouseup', handleMouseUp);
                    }}
                  />
                )}

                {/* 右侧预览 */}
                {!isEditMode && (
                  <motion.div 
                    initial={{ opacity: 0, x: 50 }}
                    animate={{ opacity: 1, x: 0 }}
                    className="flex flex-col h-full"
                    style={{ 
                      width: isFullscreen ? '50%' : '50%', 
                      minWidth: isFullscreen ? '400px' : '300px' 
                    }}
                    ref={previewRef}
                  >
                    <div className={cn(
                      "flex-shrink-0 p-2 border-b rounded-t-xl",
                      isDark ? "bg-gray-800/80 border-gray-700" : "bg-white/80 border-gray-200"
                    )}>
                      <motion.button
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                        onClick={() => setIsEditMode(true)}
                        className="text-sm font-medium text-gray-600 dark:text-gray-400 flex items-center hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                        title="切换到编辑模式"
                      >
                        <i className="fa-solid fa-eye mr-2"></i>
                        预览区域
                      </motion.button>
                    </div>
                    <div className={cn(
                      "flex-1 overflow-hidden rounded-b-xl shadow-xl preview-container",
                      isDark ? "bg-gray-900/80" : "bg-white/80"
                    )}>
                      <div className={cn(
                        "w-full h-full overflow-y-auto custom-scrollbar",
                        isDark ? "bg-gray-900/80" : "bg-white/80"
                      )}>
                        <div className="p-6 max-w-5xl mx-auto">
                          <MilkdownPreview 
                            content={content || "请编辑文档内容"}
                            isDark={isDark}
                            className="text-base"
                          />
                        </div>
                      </div>
                    </div>
                  </motion.div>
                )}
              </div>
            </main>

            {/* 底部工具栏 */}
            <motion.div 
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className={cn(
                "flex-shrink-0 p-2 border-t backdrop-blur-xl bg-opacity-95",
                isDark ? "bg-gray-800/95 border-gray-700" : "bg-white/95 border-gray-200"
              )}
            >
              <div className="container mx-auto flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
                <div className="flex items-center space-x-6">
                  {!isFullscreen && (
                    <>
                  <span className="flex items-center">
                    <i className="fa-solid fa-keyboard mr-2 text-blue-500"></i>
                    支持所有 Markdown 语法
                  </span>
                  <span className="flex items-center">
                    <i className="fa-solid fa-clock mr-2 text-green-500"></i>
                    实时预览
                  </span>
                    </>
                  )}
                  <span className="flex items-center">
                    <i className="fa-solid fa-chart-line mr-2 text-purple-500"></i>
                    字数统计
                  </span>
                </div>
                <div className="flex items-center space-x-3">
                  <span className="font-medium">快捷键:</span>
                  <kbd className="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-700 rounded-lg shadow-inner font-mono">
                    Ctrl+S
                  </kbd>
                  <span>保存文档</span>
                  {isFullscreen && (
                    <>
                      <kbd className="px-3 py-1 text-xs bg-gray-200 dark:bg-gray-700 rounded-lg shadow-inner font-mono">
                        ESC
                      </kbd>
                      <span>退出全屏</span>
                    </>
                  )}
                </div>
              </div>
            </motion.div>

            {/* 表格配置弹框 */}
            <AnimatePresence>
              {showTableModal && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
                  style={{ top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}
                  onClick={() => setShowTableModal(false)}
                >
                  <motion.div
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0.9, opacity: 0 }}
                    className={cn(
                      "w-full max-w-sm p-4 rounded-2xl shadow-2xl",
                      isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
                    )}
                    onClick={(e) => e.stopPropagation()}
                  >
                    <div className="flex items-center justify-between mb-4">
                      <h3 className={cn(
                        "text-xl font-bold",
                        isDark ? "text-white" : "text-gray-900"
                      )}>
                        <i className="fa-solid fa-table mr-3 text-blue-500"></i>
                        插入表格
                      </h3>
                      <button
                        onClick={() => setShowTableModal(false)}
                        className={cn(
                          "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                          isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                        )}
                      >
                        <i className="fa-solid fa-times"></i>
                      </button>
                    </div>

                    <div className="space-y-4">
                      {/* 行数设置 */}
                      <div>
                        <label className={cn(
                          "block text-sm font-medium mb-2",
                          isDark ? "text-gray-300" : "text-gray-700"
                        )}>
                          行数
                        </label>
                        <input
                          type="number"
                          min="1"
                          max="20"
                          value={tableConfig.rows}
                          onChange={(e) => setTableConfig(prev => ({ ...prev, rows: parseInt(e.target.value) || 1 }))}
                          className={cn(
                            "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2",
                            isDark 
                              ? "bg-gray-700 border-gray-600 text-white focus:ring-blue-500 focus:border-blue-500" 
                              : "bg-white border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500"
                          )}
                        />
                      </div>

                      {/* 列数设置 */}
                      <div>
                        <label className={cn(
                          "block text-sm font-medium mb-2",
                          isDark ? "text-gray-300" : "text-gray-700"
                        )}>
                          列数
                        </label>
                        <input
                          type="number"
                          min="1"
                          max="10"
                          value={tableConfig.cols}
                          onChange={(e) => setTableConfig(prev => ({ ...prev, cols: parseInt(e.target.value) || 1 }))}
                          className={cn(
                            "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2",
                            isDark 
                              ? "bg-gray-700 border-gray-600 text-white focus:ring-blue-500 focus:border-blue-500" 
                              : "bg-white border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500"
                          )}
                        />
                      </div>

                      {/* 对齐方式设置 */}
                      <div>
                        <label className={cn(
                          "block text-sm font-medium mb-2",
                          isDark ? "text-gray-300" : "text-gray-700"
                        )}>
                          对齐方式
                        </label>
                        <div className="grid grid-cols-2 gap-2">
                          {[
                            { value: 'default', label: '两边对齐', icon: 'fa-solid fa-arrows-left-right' },
                            { value: 'left', label: '左对齐', icon: 'fa-solid fa-align-left' },
                            { value: 'center', label: '居中对齐', icon: 'fa-solid fa-align-center' },
                            { value: 'right', label: '右对齐', icon: 'fa-solid fa-align-right' }
                          ].map((option) => (
                            <button
                              key={option.value}
                              onClick={() => setTableConfig(prev => ({ ...prev, alignment: option.value }))}
                              className={cn(
                                "px-3 py-2 rounded-lg border transition-all duration-200 flex items-center justify-center space-x-2",
                                tableConfig.alignment === option.value
                                  ? "border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400"
                                  : isDark
                                    ? "border-gray-600 bg-gray-700 text-gray-300 hover:bg-gray-600"
                                    : "border-gray-300 bg-white text-gray-700 hover:bg-gray-50"
                              )}
                            >
                              <i className={option.icon}></i>
                              <span className="text-sm">{option.label}</span>
                            </button>
                          ))}
                        </div>
                      </div>

                      {/* 预览 */}
                      <div>
                        <label className={cn(
                          "block text-sm font-medium mb-2",
                          isDark ? "text-gray-300" : "text-gray-700"
                        )}>
                          预览
                        </label>
                        <div className={cn(
                          "p-3 rounded-lg border text-xs font-mono overflow-x-auto",
                          isDark ? "bg-gray-900 border-gray-600 text-gray-300" : "bg-gray-50 border-gray-300 text-gray-700"
                        )}>
                          <pre>{generateTable(tableConfig.rows, tableConfig.cols, tableConfig.alignment)}</pre>
                        </div>
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex space-x-3 mt-4">
                      <motion.button
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        onClick={() => setShowTableModal(false)}
                        className={cn(
                          "flex-1 px-4 py-2 rounded-lg font-medium transition-colors",
                          isDark 
                            ? "bg-gray-700 hover:bg-gray-600 text-gray-300" 
                            : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                        )}
                      >
                        取消
                      </motion.button>
                      <motion.button
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        onClick={insertTable}
                        className="flex-1 px-4 py-2 rounded-lg font-medium bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white transition-all duration-200 shadow-lg"
                      >
                        <i className="fa-solid fa-plus mr-2"></i>
                        插入表格
                      </motion.button>
                    </div>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* 代码块配置弹框 */}
            <AnimatePresence>
              {showCodeBlockModal && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
                  onClick={() => setShowCodeBlockModal(false)}
                >
                  <motion.div
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0.9, opacity: 0 }}
                    className={cn(
                      "w-full max-w-sm p-4 rounded-2xl shadow-2xl",
                      isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
                    )}
                    onClick={(e) => e.stopPropagation()}
                  >
                    <div className="flex items-center justify-between mb-4">
                      <h3 className={cn(
                        "text-xl font-bold",
                        isDark ? "text-white" : "text-gray-900"
                      )}>
                        <i className="fa-solid fa-code mr-3 text-blue-500"></i>
                        插入多语言代码块
                      </h3>
                      <button
                        onClick={() => setShowCodeBlockModal(false)}
                        className={cn(
                          "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                          isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                        )}
                      >
                        <i className="fa-solid fa-times"></i>
                      </button>
                    </div>

                    <div className="space-y-4">
                      {/* 语言选择 */}
                      <div>
                        <label className={cn(
                          "block text-sm font-medium mb-2",
                          isDark ? "text-gray-300" : "text-gray-700"
                        )}>
                          语言
                        </label>
                        <select
                          value={selectedLanguage}
                          onChange={(e) => setSelectedLanguage(e.target.value)}
                          className={cn(
                            "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2",
                            isDark 
                              ? "bg-gray-700 border-gray-600 text-white focus:ring-blue-500 focus:border-blue-500" 
                              : "bg-white border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500"
                          )}
                        >
                          <option value="json">JSON</option>
                          <option value="python">Python</option>
                          <option value="javascript">JavaScript</option>
                          <option value="java">Java</option>
                          <option value="csharp">C#</option>
                          <option value="go">Go</option>
                          <option value="ruby">Ruby</option>
                          <option value="php">PHP</option>
                          <option value="html">HTML</option>
                          <option value="css">CSS</option>
                          <option value="sql">SQL</option>
                          <option value="bash">Bash</option>
                          <option value="markdown">Markdown</option>
                        </select>
                      </div>

                      {/* 代码内容 */}
                      <div>
                        <label className={cn(
                          "block text-sm font-medium mb-2",
                          isDark ? "text-gray-300" : "text-gray-700"
                        )}>
                          代码内容
                        </label>
                        <textarea
                          value={codeBlockContent}
                          onChange={(e) => setCodeBlockContent(e.target.value)}
                          rows={8}
                          placeholder="在此输入代码内容..."
                          className={cn(
                            "w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2 font-mono text-sm",
                            isDark 
                              ? "bg-gray-700 border-gray-600 text-white focus:ring-blue-500 focus:border-blue-500" 
                              : "bg-white border-gray-300 text-gray-900 focus:ring-blue-500 focus:border-blue-500"
                          )}
                        />
                      </div>
                    </div>

                    {/* 操作按钮 */}
                    <div className="flex space-x-3 mt-4">
                      <motion.button
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        onClick={() => setShowCodeBlockModal(false)}
                        className={cn(
                          "flex-1 px-4 py-2 rounded-lg font-medium transition-colors",
                          isDark 
                            ? "bg-gray-700 hover:bg-gray-600 text-gray-300" 
                            : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                        )}
                      >
                        取消
                      </motion.button>
                      <motion.button
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                        onClick={confirmCodeBlock}
                        className="flex-1 px-4 py-2 rounded-lg font-medium bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white transition-all duration-200 shadow-lg"
                      >
                        <i className="fa-solid fa-plus mr-2"></i>
                        插入代码块
                      </motion.button>
                    </div>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* 表情包选择器弹框 */}
            <AnimatePresence>
              {showEmojiModal && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="fixed inset-0 z-50 flex items-center justify-center p-4"
                  style={{ top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}
                  onClick={() => setShowEmojiModal(false)}
                >
                  <motion.div
                    initial={{ scale: 0.9, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0.9, opacity: 0 }}
                    className={cn(
                      "w-full max-w-2xl p-6 rounded-2xl shadow-2xl max-h-[85vh] overflow-hidden flex flex-col",
                      isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
                    )}
                    onClick={(e) => e.stopPropagation()}
                  >
                    <div className="flex items-center justify-between mb-4 flex-shrink-0">
                      <h3 className={cn(
                        "text-xl font-bold",
                        isDark ? "text-white" : "text-gray-900"
                      )}>
                        <span className="mr-3">😊</span>
                        选择表情包
                      </h3>
                      <button
                        onClick={() => setShowEmojiModal(false)}
                        className={cn(
                          "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                          isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                        )}
                      >
                        <i className="fa-solid fa-times"></i>
                      </button>
                    </div>

                    {/* 分类标签 */}
                    <div className="flex flex-wrap gap-2 mb-4 pb-4 border-b flex-shrink-0">
                      {emojiCategories.map((category, index) => (
                        <motion.button
                          key={category.name}
                          whileHover={{ scale: 1.05 }}
                          whileTap={{ scale: 0.95 }}
                          className={cn(
                            "px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 flex items-center space-x-2",
                            index === selectedCategory
                              ? "bg-blue-500 text-white shadow-lg"
                              : isDark
                                ? "bg-gray-700 text-gray-300 hover:bg-gray-600"
                                : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                          )}
                          onClick={() => setSelectedCategory(index)}
                        >
                          <span className="text-lg">{category.icon}</span>
                          <span>{category.name}</span>
                        </motion.button>
                      ))}
                    </div>

                    {/* 表情包网格 */}
                    <div className="grid grid-cols-10 gap-2 overflow-y-auto custom-scrollbar flex-1 min-h-0">
                      {emojiCategories[selectedCategory]?.emojis.map((emoji, index) => (
                        <motion.button
                          key={`${selectedCategory}-${index}`}
                          whileHover={{ scale: 1.2 }}
                          whileTap={{ scale: 0.9 }}
                          className={cn(
                            "w-10 h-10 rounded-lg flex items-center justify-center text-xl transition-all duration-200",
                            isDark 
                              ? "hover:bg-gray-700 hover:shadow-lg" 
                              : "hover:bg-gray-200 hover:shadow-md"
                          )}
                          onClick={() => {
                            const textarea = document.querySelector('textarea') as HTMLTextAreaElement;
                            if (textarea) {
                              const start = textarea.selectionStart;
                              const newText = content.substring(0, start) + emoji + content.substring(start);
                              handleToolbarContentChange(newText);
                              
                              // 设置光标位置
                              setTimeout(() => {
                                textarea.focus();
                                textarea.setSelectionRange(start + emoji.length, start + emoji.length);
                              }, 0);
                            }
                            setShowEmojiModal(false);
                          }}
                          title={emoji}
                        >
                          {emoji}
                        </motion.button>
                      ))}
                    </div>

                    {/* 底部提示 */}
                    <div className="mt-4 pt-4 border-t text-center flex-shrink-0">
                      <p className={cn(
                        "text-sm",
                        isDark ? "text-gray-400" : "text-gray-600"
                      )}>
                        点击表情包即可插入到文档中
                      </p>
                    </div>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* 模板弹窗 */}
            {showTemplateModal && (
              console.log('模板弹窗渲染，templates:', templates),
              <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4" onClick={() => setShowTemplateModal(false)}>
                <div
                  className={cn(
                    "w-full max-w-2xl p-6 rounded-2xl shadow-2xl max-h-[80vh] overflow-hidden",
                    isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
                  )}
                  onClick={e => e.stopPropagation()}
                >
                  <div className="flex items-center justify-between mb-4">
                    <h3 className={cn("text-xl font-bold", isDark ? "text-white" : "text-gray-900")}>选择模板</h3>
                    <button onClick={() => setShowTemplateModal(false)} className={cn("w-8 h-8 rounded-full flex items-center justify-center transition-colors", isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600")}> <i className="fa-solid fa-times"></i> </button>
                  </div>
                  {/* 模板类型切换 */}
                  <div className="flex space-x-2 mb-4">
                    {[{ type: 'SELF', label: '我的模板', icon: 'fa-solid fa-user' }, { type: 'SYS', label: '系统模板', icon: 'fa-solid fa-cog' }].map(item => (
                      <button
                        key={item.type}
                        onClick={() => {
                          setSelectedTemplateType(item.type as 'SELF' | 'SYS');
                          loadTemplates(item.type as 'SELF' | 'SYS');
                        }}
                        className={cn(
                          "px-4 py-2 rounded-lg font-medium flex items-center space-x-2",
                          selectedTemplateType === item.type ? "bg-green-500 text-white shadow-lg" : isDark ? "bg-gray-700 text-gray-300 hover:bg-gray-600" : "bg-gray-200 text-gray-700 hover:bg-gray-300"
                        )}
                      >
                        <i className={item.icon}></i>
                        <span>{item.label}</span>
                      </button>
                    ))}
                  </div>
                  {/* 模板列表 */}
                  <div className="max-h-96 overflow-y-auto custom-scrollbar">
                    {isLoadingTemplates ? (
                      <div className="flex items-center justify-center h-32"><i className="fa-solid fa-spinner fa-spin text-2xl mr-2"></i><span>加载模板中...</span></div>
                    ) : templates.length === 0 ? (
                      <div className="text-center py-8"><i className="fa-solid fa-inbox text-4xl text-gray-400 mb-2"></i><p className="text-gray-500">暂无模板</p></div>
                    ) : (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {templates.map(template => (
                          <div key={template.tmpId} className={cn("p-4 rounded-lg border transition-all duration-200 cursor-pointer", isDark ? "bg-gray-700 border-gray-600 hover:bg-gray-600" : "bg-gray-50 border-gray-200 hover:bg-gray-100") }>
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <h4 className={cn("font-medium mb-2", isDark ? "text-white" : "text-gray-900")}>{template.tmpTitle}</h4>
                                <div className={cn("text-xs mb-1", isDark ? "text-gray-400" : "text-gray-600")}>创建人：{template.createUser || '-'}</div>
                                <div className={cn("text-xs", isDark ? "text-gray-400" : "text-gray-600")}>创建时间：{template.createTime ? new Date(template.createTime).toLocaleString() : '-'}</div>
                              </div>
                              <div className="flex space-x-2 ml-4">
                                <button onClick={() => handleApplyTemplate(template)} className={cn("w-8 h-8 rounded-full flex items-center justify-center transition-colors", isDark ? "bg-green-600 hover:bg-green-700 text-white" : "bg-green-500 hover:bg-green-600 text-white") } title="应用模板"><i className="fa-solid fa-check text-sm"></i></button>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}

            {showSaveTemplateModal && (
              <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4" onClick={() => setShowSaveTemplateModal(false)}>
                <div
                  className={cn(
                    "w-full max-w-md p-6 rounded-2xl shadow-2xl",
                    isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
                  )}
                  onClick={e => e.stopPropagation()}
                >
                  <div className="flex items-center justify-between mb-4">
                    <h3 className={cn("text-xl font-bold", isDark ? "text-white" : "text-gray-900")}>保存为模板</h3>
                    <button onClick={() => setShowSaveTemplateModal(false)} className={cn("w-8 h-8 rounded-full flex items-center justify-center transition-colors", isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600")}> <i className="fa-solid fa-times"></i> </button>
                  </div>
                  <div className="space-y-4">
                    <div>
                      <label className={cn("block text-sm font-medium mb-2", isDark ? "text-gray-300" : "text-gray-700")}>模板标题</label>
                      <input
                        type="text"
                        value={templateTitle}
                        onChange={e => setTemplateTitle(e.target.value)}
                        placeholder="请输入模板标题"
                        className={cn("w-full px-3 py-2 rounded-lg border transition-colors focus:outline-none focus:ring-2", isDark ? "bg-gray-700 border-gray-600 text-white focus:ring-purple-500 focus:border-purple-500" : "bg-white border-gray-300 text-gray-900 focus:ring-purple-500 focus:border-purple-500")}
                        autoFocus
                      />
                    </div>
                    <div>
                      <label className={cn("block text-sm font-medium mb-2", isDark ? "text-gray-300" : "text-gray-700")}>预览内容</label>
                      <div className={cn("p-3 rounded-lg border text-sm max-h-32 overflow-y-auto", isDark ? "bg-gray-900 border-gray-600 text-gray-300" : "bg-gray-50 border-gray-300 text-gray-700")}>{content.substring(0, 200)}...</div>
                    </div>
                  </div>
                  <div className="flex space-x-3 mt-6">
                    <motion.button
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                      onClick={() => setShowSaveTemplateModal(false)}
                      className={cn("flex-1 px-4 py-2 rounded-lg font-medium transition-colors", isDark ? "bg-gray-700 hover:bg-gray-600 text-gray-300" : "bg-gray-200 hover:bg-gray-300 text-gray-700")}
                    >取消</motion.button>
                    <motion.button
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                      onClick={handleSaveAsTemplate}
                      className="flex-1 px-4 py-2 rounded-lg font-medium bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white transition-all duration-200 shadow-lg"
                    >
                      <i className="fa-solid fa-save mr-2"></i>保存模板
                    </motion.button>
                  </div>
                </div>
              </div>
            )}
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
} 